package com.qf.smsplatform.webmaster.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.webmaster.dto.R;
import com.qf.smsplatform.webmaster.mapper.MenuMapper;
import com.qf.smsplatform.webmaster.pojo.MyAuthUser;
import com.qf.smsplatform.webmaster.pojo.TMenu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MySuccessHandler extends SimpleUrlAuthenticationSuccessHandler {

    private MenuMapper menuMapper;

    private ObjectMapper objectMapper;

    @Autowired
    public void setMenuMapper(MenuMapper menuMapper){
        this.menuMapper = menuMapper;
    }

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper){
        this.objectMapper = objectMapper;
    }

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        super.onAuthenticationSuccess(request, response, authentication);
        System.err.println("登录成功了");
        //获取当前登录成功的用户的权限
        Object principal = authentication.getPrincipal();
        System.err.println(principal);
        Long userId = ((MyAuthUser) principal).getId();

        List<TMenu> menuList = menuMapper.findAllMenusByUserId(userId);

        List<SimpleGrantedAuthority> authorityList = menuList.stream()
                .filter(menu-> !ObjectUtils.isEmpty(menu.getPerms()))//只保留有权限的数据
                .map(TMenu::getPerms)//将当前集合中符合要求的数据通过getPerms转成字符串集合
                .map(SimpleGrantedAuthority::new)//将字符串集合遍历将权限设置 进去转换为权限对象
                .collect(Collectors.toList());

        //重新设置认证的相关信息
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(principal, authentication.getCredentials(),authorityList));

        R r = R.setOk();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(objectMapper.writeValueAsString(r));

    }
}
